<template>
  <div>
    <van-nav-bar
      title="标题"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form @submit="onSubmit" ref="form">
      <van-cell-group inset>
        <van-field
          v-model="form.loginname"
          type="tel"
          name="loginname"
          label="用户名"
          placeholder="用户名"
          :rules="rules.loginname"
        />
        <van-field
          v-model="form.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="rules.password"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          block
          type="danger"
          native-type="submit"
          style="border-radius: 20px"
        >
          提交
        </van-button>
      </div>
      <span class="sp1">去注册</span>
      <van-nav-bar left-arrow @click="goRegister">
        <template #left>
          <span>快速注册</span>
        </template>
        <template #right>
          <van-icon name="arrow" />
        </template>
      </van-nav-bar>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from "../../service/user.js";
export default {
  data() {
    return {
      flag: 0, // 0 登录  1我的
      form: {
        loginname: "",
        password: "",
      },

      rules: {
        loginname: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            // 自定义校验规则
            validator: (val) => {
              return /^1[3456789]\d{9}$/.test(val);
            },
            message: "请输入正确格式的用户名(手机号)",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            // 自定义校验规则
            validator: (val) => {
              return /^.*(?=.{6,12})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[!@#$%^&*?\(\)]).*$/.test(
                val
              );
            },
            message:
              "注册密码6-12位，必须包含数字、大小写字母以及特殊字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      userLogin(this.form).then((res) => {
        console.log(res.data);
        if (res.data.code === "200") {
          this.flag = 1;
          // 存储token
          localStorage.setItem("token",res.data.data.token);
          localStorage.setItem("userid",res.data.data.userid);
          // 将登录后的用户消息存储到本地
          this.$store.commit("setUserInfo",res.data)
          this.$router.push({ path: "/home", query: { flag: this.flag } });
        }
      });
    },
    onClickLeft() {
      history.back('/home');
    },
    goRegister() {
      this.$router.push("/register");
    },
  },
};
</script>
<style scoped>
.van-nav-bar {
  margin-bottom: 20px;
}
.sp1 {
  font-size: 16px;
  color: gray;
  margin-left: 20px;
}
</style>
